import React from "react";
import './index.less';
import logo from '@/assets/logo-full.png';
import { useLocation } from '@umijs/max';
import {
    ActionType, PageContainer, ProColumns, ProTable, ModalForm, DrawerForm,
    ProList, ProFormTextArea, ProField,
} from "@ant-design/pro-components";
import { columns, loadTableData, loadListData } from "./props";
import { stateSet, executeTask, processDynamics, nodeInfo } from "./props/service";
import { Button, Space, Tag, Descriptions, Modal, Popover, Card, Avatar } from "antd";
import { useModel } from "@umijs/max";
import { EasyExecute, EasyComment } from './components';
import { FileImageTwoTone } from "@ant-design/icons";
import { EasyFlowableViewer } from 'easy-flowable-react';

export default () => {

    const { initialState } = useModel('@@initialState');
    const listRef = React.useRef<ActionType>();
    const { users, groups } = initialState;
    const { state }: any = useLocation();
    const table = React.useRef<ActionType>();
    const [open, setOpen] = React.useState<boolean>(false);
    const [viewer, setViewer] = React.useState<{ open: boolean; processInstanceId: string; processDefinitionId: string; }>({
        open: false,
        processInstanceId: '',
        processDefinitionId: ''
    });

    React.useEffect(() => {
        if (!open) {
            table.current?.reloadAndRest();
        }
    }, [open]);

    const actionColumns: ProColumns[] = [{
        title: '操作',
        align: 'center',
        render: (dom, entity) => <Space>
            <Button onClick={() => setViewer({
                open: true, processInstanceId:
                entity.processInstanceId,
                processDefinitionId: entity.processDefinitionId
            }) } type="link" icon={<FileImageTwoTone/>}>流程动态</Button>
            <Button onClick={ async () => {
                const { success } = await stateSet(entity.processInstanceId);
                if (success) {
                    table.current?.reloadAndRest();
                }
            } } style={{ color: entity.status ? '#87d068' : '#ff4d4f' }} type='text'>
                {entity.status ? '激活' : '挂起'}
            </Button>
            <DrawerForm
                title={entity.name}
                open={open}
                onOpenChange={() => table.current?.reloadAndRest()}
                drawerProps={{ destroyOnClose: true }}
                submitter={{
                    resetButtonProps: false,
                    searchConfig: { submitText: '执行' },
                    render: (props, dom) => <Space>
                        <EasyExecute {...entity} reload={() => {
                            table.current?.reloadAndRest();
                            listRef.current?.reloadAndRest();
                        }}/>
                        <ModalForm
                            width="25%"
                            onFinish={async (values) => {
                                const { success } = await executeTask({
                                    ...values, flowCommentType: 'CANCELLATION',
                                    processInstanceId: entity.processInstanceId,
                                    taskId: entity.taskId
                                });
                                setOpen(false);
                                table.current?.reloadAndRest();
                                return success;
                            }}
                            trigger={<Button disabled={entity.status || !entity.taskId} type="primary" danger>流程作废</Button>}>
                            <ProFormTextArea name="commentContent" label="作废原因" rules={[{ required: true, message: '作废原因不能为空' }]}/>
                        </ModalForm>
                    </Space>
                }}
                trigger={<Button type='text' style={{ color: 'purple' }}>执行历史</Button>}>
                <ProList
                    grid={{ column: 1 }}
                    actionRef={listRef}
                    params={{ processInstanceId: entity.processInstanceId }}
                    metas={{
                        avatar: {
                            render: (dom, { duration, assignee }) => {
                                if (duration || duration === 0) {
                                    if (duration < 1000) {
                                        return <Tag color='success'>耗时：{duration}毫秒</Tag>
                                    } else if (duration >= 1000 && duration < 60 * 1000) {
                                        return <Tag color='success'>耗时：{duration/1000}秒</Tag>
                                    } else if (duration >= 60 * 1000 && duration < 60 * 60 * 1000) {
                                        return <Tag color='success'>耗时：{(duration/(60 * 1000)).toFixed(0)}分钟</Tag>
                                    } else if (duration >= 60 * 60 * 1000 && duration < 24 * 60 * 60 * 1000) {
                                        return <Tag color='success'>耗时：{(duration/(60 * 60 * 1000)).toFixed(2)}小时</Tag>
                                    } else if (duration >= 24 * 60 * 60 * 1000) {
                                        return <Tag color='warning'>耗时：{(duration/(24 * 60 * 60 * 1000)).toFixed(2)}天</Tag>
                                    }
                                }
                                return <Tag color='orange'>{assignee ? '待办' : '任务待签收'}</Tag>
                            }
                        },
                        title: {
                            dataIndex: 'taskName'
                        },
                        subTitle: {
                            dataIndex: 'assignee',
                            render: (dom, { assignee, candidateUsers, candidateGroups }) => {
                                if (candidateGroups && candidateGroups.length) {
                                    return <Tag color="purple">候选组:
                                        <ProField text={candidateGroups} mode="read" request={() => groups}/>
                                    </Tag>
                                }
                                return <Tag color="purple">
                                    {assignee ? '执行人: ' : '候选人: '}
                                    <ProField text={assignee ?? candidateUsers} mode="read" request={() => users}/>
                                </Tag>
                            }
                        },
                        content: {
                            render: (dom, entity) => <Descriptions column={3}>
                                <Descriptions.Item label="任务节点">{entity.taskDefKey}</Descriptions.Item>
                                <Descriptions.Item label="开始时间">{entity.startTime}</Descriptions.Item>
                                <Descriptions.Item label="结束时间">{entity.endTime}</Descriptions.Item>
                            </Descriptions>
                        },
                        actions: {
                            render: (dom, { comments, taskName, taskId, endTime }) => <Space>
                                { (comments && comments.length) ? <EasyComment comments={comments} taskName={taskName}/> : null }
                                { (entity.taskIds && !endTime) ?
                                    <EasyExecute { ...entity } link taskId={taskId} reload={() => {
                                        table.current?.reloadAndRest();
                                        listRef.current?.reloadAndRest();
                                    }}/> : null }
                            </Space>
                        }
                    }}
                    rowKey="historyId"
                    request={loadListData}/>
            </DrawerForm>
        </Space>
    }];

    return <PageContainer>
        <ProTable
            headerTitle={state?.name || '流程运行实例列表'}
            params={{ processDefinitionId: state?.processDefinitionId }}
            request={loadTableData}
            search={false}
            scroll={{ y: 600 }}
            columns={columns(users).concat(actionColumns)}
            pagination={false}
            rowKey="processInstanceId"
            actionRef={table}/>
        <Modal
            open={viewer.open}
            width="60%"
            centered
            destroyOnClose
            keyboard mask={false} footer={false}
            onCancel={() => setViewer({ ...viewer, open: false })}>
            <EasyFlowableViewer
                mode="active"
                height={70}
                onClick={async (id) => {
                    const { result } = await nodeInfo(id);
                    return {
                        ...result,
                        users: <Space>
                            { (result?.users || []).map((i: any, index) => <Popover
                                key={'user_' + index}
                                title="执行人"
                                content={<Card title={false}>
                                    <Avatar src={i.avatar || logo}/>
                                    <span>邮箱：{i.email}</span><br/>
                                </Card>}>
                                <Tag color="warning">{ i.username }</Tag>
                            </Popover>) }
                        </Space>,
                    };
                }}
                request={async () => {
                    if (viewer.open) {
                        const {success, result} = await processDynamics({
                            processInstanceId: viewer.processInstanceId,
                            processDefinitionId: viewer.processDefinitionId
                        });
                        return result;
                    }
                    return '';
                }}
                excludeType={['SequenceFlow', 'InclusiveGateway']}/>
        </Modal>
    </PageContainer>

}